package com.lwh.easyExcel.controller;


import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lwh.common.util.DateUtil;
import com.lwh.easyExcel.entity.BdCheliangEntity;
import com.lwh.easyExcel.service.BdCheliangService;
import com.lwh.easypoi.util.EasyPoiUtil;
import com.sun.deploy.net.URLEncoder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
import java.io.*;
import java.util.*;
import java.util.concurrent.Callable;


/**
 * @Title: Controller
 * @Description: 车辆管理
 * @author
 * @date
 * @version
 *
 */
@Controller
@RequestMapping("/bdCheliang")
public class BdCheliangController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BdCheliangController.class);

	@Autowired
	private BdCheliangService bdCheliangService;

	@Autowired
	private Validator validator;

	// 查询页面内容
	@RequestMapping("/findPage")
	@ResponseBody
	public Callable<Map<String, Object>> findPage(BdCheliangEntity query) {

		if (query.getPage() == null) {
			query.setPage(1);
		}
		if (query.getRows() == null) {
			query.setRows(10);
		}
		Callable<Map<String, Object>> callable = (() -> bdCheliangService.findPage(query));
		return callable;
	}

	/**
	 * 增加功能
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/addCheliang")
	@ResponseBody
	public Callable<String> add(BdCheliangEntity bdCheliangEntity) {

		Callable<String> callable = null;

		try {
			bdCheliangService.insertSelective(bdCheliangEntity);
			callable = () -> {
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统出错了";
			};
		}
		return callable;
	}

	// 修改
	@PostMapping("/updateCheliang")
	@ResponseBody
	public Callable<String> update(BdCheliangEntity adCheliangEntity) {

		Callable<String> callable = null;
		if (adCheliangEntity.getId() == null) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.updateByPrimaryKeySelective(adCheliangEntity);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}

	// 导入
	@RequestMapping("/importExcel")
	@ResponseBody
	public String importExcel(MultipartFile uploadFile) {
		String result = null;
		InputStream is = null;
		try {
			String filename = uploadFile.getOriginalFilename();
			if (filename != null && (filename.toLowerCase().endsWith(".xls") || filename.toLowerCase().endsWith(".xlsx"))) {
				is = new BufferedInputStream(uploadFile.getInputStream());
			} else {
				return "导入的文件不是excel文件";
			}
			result = bdCheliangService.readExcel(is);
		} catch (Exception e) {
			e.printStackTrace();
			return "系统发生错误";
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	// 批量删除
	@RequestMapping("/deleteCheliang")
	@ResponseBody
	public Callable<String> delete(String[] ids) {
		Callable<String> callable = null;
		if (ids == null || ids.length == 0) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.deleteByIds(ids);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}

	// 单独删除
	@RequestMapping("/deleteOneCheliang")
	@ResponseBody
	public Callable<String> deleteOne(String id) {
		Callable<String> callable = null;
		if (id == null) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.deleteOneById(id);
				return "删除成功";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}


	// 导出
	@RequestMapping("/exportExcel")
	@ResponseBody
	public Map<String, Object> outExcel(BdCheliangEntity bdCheliangEntity) {

		return bdCheliangService.outExcel(bdCheliangEntity);
	}



	// 模板下载
	@RequestMapping("/modelExcel")
	@ResponseBody
	public void modelExcel(HttpServletResponse response) {


		List<BdCheliangEntity> list = new ArrayList<>();
		try {

			createExcelStreamMutilByEaysExcel(response, list, ExcelTypeEnum.XLS, "车辆信息.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @Author
	 * @Description 导出excel 支持一张表导出多个sheet
	 * @Param OutputStream 输出流
	 * Map<String, List>  sheetName和每个sheet的数据
	 * ExcelTypeEnum 要导出的excel的类型 有ExcelTypeEnum.xls 和有ExcelTypeEnum.xlsx
	 */
	public static void createExcelStreamMutilByEaysExcel(HttpServletResponse response, List<BdCheliangEntity> list, ExcelTypeEnum type, String fileName) throws UnsupportedEncodingException {
		try {
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
			ServletOutputStream out = response.getOutputStream();
			ExcelWriter writer = new ExcelWriter(out, type, true);
			setSheet(list, writer);
			writer.finish();
			out.flush();
			System.out.println("导出完成");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * @Author jian
	 * @Description //setSheet数据
	 */
	private static void setSheet(List<BdCheliangEntity> list, ExcelWriter writer) {
		int sheetNum = 1;

			Sheet sheet = new Sheet(sheetNum, 0,BdCheliangEntity.class);
			sheet.setSheetName("车辆管理");
			writer.write(list, sheet);


		}
	}





